<template>
  <view class="category-container">
    <!-- 顶部操作栏 -->
    <view class="action-bar">
      <button class="add-button" @click="showAddModal">添加分类</button>
    </view>

    <!-- 分类列表 -->
    <view class="category-list">
      <!-- 调试信息 -->
      <view class="debug-info" style="padding: 10rpx; background: #f0f0f0; font-size: 24rpx; color: #666;">
        当前加载了 {{ categoryCount }} 个分类
      </view>
      
      <view v-if="isLoading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>
      <view v-else-if="categories.length === 0" class="empty-state">
        <text class="empty-text">暂无分类数据</text>
        <text class="empty-tip">点击上方"添加分类"按钮创建第一个分类</text>
      </view>
      <view class="category-item" v-for="(category, index) in categories" :key="index">
        <view class="category-info">
          <text class="category-name">{{ category.dtName }}</text>
        </view>
        <view class="category-actions">
          <button class="action-btn edit" @click="editCategory(category)">编辑</button>
          <button class="action-btn delete" @click="deleteCategory(category)">删除</button>
        </view>
      </view>
    </view>

    <!-- 添加/编辑分类弹窗 -->
    <uni-popup ref="popup" type="center">
      <view class="popup-content">
        <view class="popup-title">{{ isEditing ? '编辑分类' : '添加分类' }}</view>
        <view class="popup-form">
          <input 
            class="form-input" 
            type="text" 
            v-model="formData.name" 
            placeholder="请输入分类名称"
          />
          <view class="form-actions">
            <button class="cancel-btn" @click="hideModal">取消</button>
            <button class="confirm-btn" @click="handleSubmit">确定</button>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { dishApi } from '../../utils/api.js'

export default {
  data() {
    return {
      categories: [],
      isLoading: false,
      isEditing: false,
      formData: {
        id: null,
        name: ''
      }
    }
  },
  onLoad() {
    this.loadCategories()
  },
  onShow() {
    // 每次显示页面时都重新加载数据，确保数据是最新的
    this.loadCategories()
  },
  computed: {
    // 调试用：显示分类数量
    categoryCount() {
      return this.categories.length
    }
  },
  methods: {
    // 加载分类列表
    async loadCategories() {
      console.log('开始加载分类列表...')
      this.isLoading = true
      
      try {
        const response = await dishApi.getDishTypes()
        
        console.log('分类列表响应:', response)
        console.log('响应数据类型:', typeof response)
        console.log('响应数据结构:', JSON.stringify(response, null, 2))
        
        if (response.code === 200) {
          // 将字符串数组转换为对象数组
          const stringArray = response.data || []
          this.categories = stringArray.map((name, index) => ({
            dtId: index + 1,  // 分类ID从1开始
            dtName: name      // 分类名称
          }))
          console.log('转换后的分类列表:', this.categories)
          console.log('分类数量:', this.categories.length)
          console.log('第一个分类:', this.categories[0])
        } else {
          console.error('获取分类列表失败:', response.message)
          uni.showToast({
            title: response.message || '获取分类列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        uni.showToast({
          title: '获取分类列表失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        console.log('加载完成，当前分类数量:', this.categories.length)
      }
    },

    showAddModal() {
      this.isEditing = false;
      this.formData = {
        id: null,
        name: ''
      };
      this.$refs.popup.open();
    },

    editCategory(category) {
      this.isEditing = true;
      this.formData = {
        id: category.dtId,
        name: category.dtName
      };
      this.$refs.popup.open();
    },

    hideModal() {
      this.$refs.popup.close();
    },

    async handleSubmit() {
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入分类名称',
          icon: 'none'
        });
        return;
      }

      try {
        let response;
        
        if (this.isEditing) {
          // 编辑分类
          response = await dishApi.updateDishType(this.formData.id, this.formData.name)
        } else {
          // 添加分类
          response = await dishApi.addDishType(this.formData.name)
        }

        if (response.code === 200) {
          this.hideModal();
          uni.showToast({
            title: this.isEditing ? '修改成功' : '添加成功',
            icon: 'success'
          });
          // 重新加载分类列表
          this.loadCategories();
        } else {
          uni.showToast({
            title: response.message || (this.isEditing ? '修改失败' : '添加失败'),
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('操作失败:', error);
        uni.showToast({
          title: this.isEditing ? '修改失败' : '添加失败',
          icon: 'none'
        });
      }
    },

    async deleteCategory(category) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该分类吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await dishApi.deleteDishType(category.dtId)

              if (response.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新加载分类列表
                this.loadCategories();
              } else {
                uni.showToast({
                  title: response.message || '删除失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error('删除失败:', error);
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    }
  }
}
</script>

<style>
.category-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.action-bar {
  margin-bottom: 20rpx;
}

.add-button {
  background-color: #C70209;
  color: #ffffff;
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
}

.category-list {
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.category-item:last-child {
  border-bottom: none;
}

.category-info {
  display: flex;
  align-items: center;
}

.category-name {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}

.category-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  font-size: 24rpx;
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  border-radius: 25rpx;
}

.action-btn.edit {
  background-color: #e6f7ff;
  color: #1890ff;
}

.action-btn.delete {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.popup-content {
  background-color: #ffffff;
  border-radius: 12rpx;
  width: 600rpx;
  padding: 30rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.popup-form {
  padding: 0 20rpx;
}

.form-input {
  background-color: #f5f5f5;
  height: 80rpx;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  margin-bottom: 30rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #C70209;
  color: #ffffff;
}

.empty-state {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.empty-tip {
  font-size: 24rpx;
}

.loading-state {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

.loading-text {
  font-size: 28rpx;
}
</style> 